package com.ivan.utils;

import cn.hutool.core.codec.Base64;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;

/**
 * @author 11900
 * @version V1.0
 * @Title: ${FILE_NAME}
 * @Package com.ivan.util
 * @Description: TODO
 * @date 2020/4/27 10:55
 */
@Data
public class JwtUtils {


    //服务器的key /** 秘钥 */
//    private final static String JWT_SECERT ="test-jwt-secret";
     private   static String JWT_SECERT ;


    /**
     * 签发JWT
     * @param id JWT唯一身份标识
     * @param iss 签发者
     * @param subject 可以是JSON数据 尽可能少 jwt所面向的用户就是用户的登录名
     * @param ttlMillis 有效期毫秒
     * @return  String
     *
     */
    public static String createJWT( String id,String iss ,String subject, long ttlMillis) {
        //设置签名算法
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        SecretKey secretKey = generalKey();
        JwtBuilder builder = Jwts.builder()
                .setId(id) //设置用户唯一标志
                .setSubject(subject)   // 主题
                .setIssuer(iss)     // 签发者
                .setIssuedAt(now)      // 签发时间
//                .claim("userName", userName) //claim就是key-value保存的map数据，像上面id,subject,issuer都是内置的KEY
//                .claim("userPower", userPower)
                .signWith(signatureAlgorithm, secretKey); // 签名算法以及密匙
        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date expDate = new Date(expMillis);
            builder.setExpiration(expDate); // 过期时间
        }
        return builder.compact();
    }
    /**
     * 验证JWT
     * @param jwtStr
     * @return
     */
    public static CheckResult validateJWT(String jwtStr) {
        CheckResult checkResult = new CheckResult();
        Claims claims = null;
        try {
            claims = parseJWT(jwtStr);
            checkResult.setSuccess(true);
            checkResult.setClaims(claims);
        } catch (Exception e) {
            checkResult.setErrCode(400);
            checkResult.setSuccess(false);
        }
        return checkResult;
    }
    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.decode(JWT_SECERT);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }
    /**
     *
     * 解析JWT字符串
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }

    public static String getJwtSecert() {
        return JWT_SECERT;
    }

    public static void setJwtSecert(String jwtSecert) {
        JWT_SECERT = jwtSecert;
    }
}
